package JUC;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.*;

/**
 * @author 曹见朋
 * @create 2024-07-03-17:29
 */
public class MyLock {

    private AtomicReference<Thread> lock = new AtomicReference<>();

    public void lock(){
        Thread thread = Thread.currentThread();
        while(!lock.compareAndSet(null, thread)){
            try {
                TimeUnit.MILLISECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void unlock(){
        Thread thread = Thread.currentThread();
        lock.compareAndSet(thread, null);
        AtomicMarkableReference atomicMarkableReference = new AtomicMarkableReference(100, false);
        AtomicStampedReference<Object> objectAtomicStampedReference = new AtomicStampedReference<>(100, 0);
        // DoubleAccumulator doubleAccumulator = new DoubleAccumulator();
        // DoubleAdder doubleAdder = new DoubleAdder();
        // LongAdder longAdder = new LongAdder();
    }

    public static void main(String[] args) {
        MyLock lock = new MyLock();

        new Thread(()->{
            lock.lock();
            System.out.println("线程1正在执行任务");
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("线程1执行任务完毕");
            lock.unlock();
        }).start();

        new Thread(()->{
            lock.lock();
            System.out.println("线程2正在执行任务");
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("线程2执行任务完毕");
            lock.unlock();
        }).start();
    }
}
